package com.app.params

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.Toast
import com.app.params.activity.ClearSeting
import com.app.params.activity.History
import com.app.params.bean.ParamsBean
import com.app.params.utlis.Constans
import com.app.params.utlis.RootCmd
import com.app.params.utlis.Sharedpreference
import com.app.params.utlis.Tools
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.FileUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject
import sql.DaoSession
import sql.ParamsBeanDao
import java.io.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


class MainActivity : AppCompatActivity() {
    /**
     *   imei                机器码(IMEI)______
     *   androidID           安卓ID(Android ID)______
     *   wifiMac             WIFI MAC地址______
     *   wifiSSID            WIFI SSID______
     *   phone               手机号______
     *   sim                 IM序列号_______
     *   imsi                机器码(IMSI)______
     *   simState            SIM状态-----
     *   firmID              运营商ID_____
     *   frimName            运营商名称
     *   cnCode              国家码
     *   model               机型(MODEL)______
     *   firm                厂商------
     *   radio               基本版本(Radio)
     *   androidClass        Android版本等级
     *   androidVersion      Android版本号
     *   fingerprint         fingerprint
     *   Board               Board-----
     *   Device              Device----
     *   Product             Product----
     *   HOST                HOST----
     *   DISPLAY             DISPLAY--------------
     *   BuildID             BuildID
     *
     */
    //机型库
    val phoneStr = "SAMSUNG&GT-I9508V&Exynos 5410, SAMSUNG&SM-G9008V&MSM8674AC, SONY&L50t&MSM8974AB, HUAWEI&h60-l01&Kirin 920, Huawei&Ascend P7&Kirin 910T, ZTE&S2002&MSM8928, LG&G2&MSM8674AB, SONY&L36h&APQ8064, Sony&L50t&MSM8974AB, NUBIA&Z5SS&MSM8674AB, ZTE&Grand SII&MSM8674AB, OPPO&X909&APQ8064, OPPO&N1&APQ8064, SAMSUNG&GT-i9508&APQ8060, Huawei&G750-T01&MT6592, XIAOMI&MI3&MSM8274AB, VIVO&Xshot&MSM8974AA, SAMSUNG&SM-N9008S&MSM8674AB, SAMSUNG&SM-G9009W&MSM8674AC, Hasee&X50 TS&MT6592, HTC&M8d&Snapdragon600, HTC&8060&Snapdragon600, Gionee&S5.5L&MT6592, Coolpad&8970L&Nvidia Tegra 4, Lenovo&K910e&MSM8674AB, Samsung&SM-N9008S&Exynos 5420, TCL&S960T&MT6592, HTC&m8sd&Snapdragon600, Samsung&SM-N9008S&MSM8674AB, LG&E730&Snapdragon600, nibiru&H1&MT6592H, Samsung&G9008W&MSM8674AC, Gionee&E7T&Snapdragon8974, Sony&L39u&MSM8674AB, Philips&i928&MT6592, Lenovo&K910&MSM8974AB, XIAOMI&MI4&MSM8974AC, OPPO&N3&MSM8974AA, Sony&L55T&MSM8974AC, SMARTISAN&T1&MSM8974AC, HTC&M8t&MSM8974AC, Nubia&NX505J&MSM8974AC, OPPO&N1&APQ8064, Sony&L50w&MSM8274AB, Sony&L36h&APQ8064, Sony&L50t&MSM8974AB, Samsung&SM-N9008V&MSM8274, Sony&L55U&MSM8974AC, LG&Nexys 5&MSM8974, Sony&XL39h&MSM8274, Lenovo&X2-TO&MT6595M, SAMSUNG&SM-C101&Exynos 5410, HTC&M8St&MSM8974AC, LG&G2&MSM8974, htc&802t&APQ8064T, HTC&802d&APQ8064T, Samsung&GT-I9508V&Exynos 5410, Samsung&GT-I9507V&Exynos 5 Octa, LG&E730&APQ8064T, nubia&NX601J&MSM8974AB, HTC&M8Sw&MSM8974AC, HTC&802w&MSM8974, HTC&8088&MSM8064T, Coolpad&7020&PXA1088, nubia&NX403A&MSM8974, HTC&M8d&MSM8974AC, HTC&M8Et&MSM8974AC, Gionee&E7&MSM8974, HTC&9060&APQ8064T, Coolpad&9970&Tegra4, HTC&M8sd&MSM8974AC, Sony&L39u&MSM8974, LG&E985T&APQ8064, Sony&L50u&MSM8974AB, Gionee&E6&MTK6589T, htc&8060&MSM8064T, ZTE&U988S&Tegra4, Lenovo&S968T&MT6589T, LG&L22&MSM8974, XIAOMI&MI3&MSM8274AB, LG&D802&MSM8974, ZTE&N988&APQ8064, SAMSUNG&G910&MSM8974, Philips&i908&MT6592, SAMSUNG&N075T&MSM8974, HTC&9088&APQ8064T, HTC&8160&MSM8064T, TCL&Y910&MT6589T, Coolpad&8970l&Tegra4, DOOV&S2&MT6592, TCL&S960T&MT6592, Coolpad&8971&MSM8974AB, Philips&W8560&MT6589T, Sony&L35h&MSM8974, TCL&Y910T&MT6592T, nubia&Z5Sn&MSM8974, Hisense&HS-X1&MSM8974AB, HTC&x920e&MSM8974AB, AUX&W1&MT6589WT, Amoi&A920W&MT6589T, Amoi&A955T&MT6591, Hasee&X55&MT6592, HTC&809D&APQ8064T, HTC&X920e&APQ8064, HTC&901e&APQ8064T, VOTO&UMI-X2&MT6589T, Sharp&SH-13C&MSM8260A"
    val phoneNum = "159|46002|898600,158|46002|898602,150|46002|898602,151|46002|898602,135|46000|898600,136|46000|898600,137|46000|898600,138|46000|898602,139|46000|898602,157|46007|898602,188|46007|898602,152|46002|898600,187|46007|898600,131|46001|898601,132|46001|898601,133|46003|898603,155|46001|898606,156|46001|898606,180|46003|898603,189|46003|898603,159|46002|898600"

    lateinit var parmas_1: List<String>
    lateinit var parmas_2: List<String>
    lateinit var random: Random
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)
        initConfit()
    }

    lateinit var share: Sharedpreference
    private lateinit var dateFormat: SimpleDateFormat
    private lateinit var paramsDao: ParamsBeanDao
    fun initConfit() {
        var app = application as App
        var configAss = assets.open("config.txt")
        share = Sharedpreference.getinitstance()
        random = Random()
        parmas_1 = ArrayList<String>()
        parmas_2 = ArrayList<String>()
        dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        paramsDao = app.parasmDao
        Runnable {
            var configTxt = readTxtFile(configAss).toString()
            var params = configTxt.split("参数2{")
            parmas_1 = params[0].substring(1, params[0].length).split(",")
            parmas_2 = params[1].substring(0, params[1].length).split(",")
        }.run()
    }

    fun dian(view: View) {
        var intent: Intent
        when (view.id) {
        //参数生成
            R.id.paramsGenerate -> {
                var editStr = edit.text.toString()
                if (TextUtils.isEmpty(editStr)) {
                    Toast.makeText(this, "请先输入一个参数", Toast.LENGTH_SHORT).show()
                } else {
                    if (editStr.length >= 3) {
                        var md5Str = EncryptUtils.encryptMD5ToString(editStr)
                        var sb = StringBuffer()
                        var md5Int: String
                        var pNum = phoneNum.split(",")
                        for (m in md5Str) {
                            sb.append(m.toInt())
                        }
                        md5Int = sb.toString()
                        imei.text = md5Int.substring(0, 15)
                        androidID.text = md5Str.subSequence(0, 16)
                        wifiMac.text = "${md5Str.substring(0, 2)}:${md5Str.substring(3, 5)}:${md5Str.substring(7, 9)}:${md5Str.substring(11, 13)}:${md5Str.substring(15, 17)}:${md5Str.substring(19, 21)}"
                        wifiSSID.text = "TP-LINK_" + getIntRandom(4)
                        var contentPosition = if (md5Int[3].toInt() >= pNum.size) {
                            pNum.size - 1
                        } else {
                            md5Int[3].toInt()
                        }
                        var conten = pNum[contentPosition].split("|")
                        phone.text = (getTel(conten[0]))
                        sim.text = getICCID(conten[2])
                        imsi.text = (getImsi(conten[1]))
                        firmID.text = conten[1]
                        simState.text = "5"
                        frimName.text = "China Mobile GSM"
                        cnCode.text = "cn"
                        var modelStr = phoneStr.split(",")
                        var modelStrdouhao: String
                        modelStrdouhao = if ((md5Int.substring(2, 3).toInt() % 2) == 0) {
                            modelStr[if ("${md5Int.substring(2, 3)}${md5Int.substring(3, 4)}".toInt() >= modelStr.size) modelStr.size - 1 else modelStr.size - 1]
                        } else {
                            modelStr[if ("${md5Int.substring(2, 3)}".toInt() >= modelStr.size) modelStr.size - 1 else modelStr.size - 1]
                        }
                        var modelStrFenHao = modelStrdouhao.split("&")
                        firm.text = modelStrFenHao[0]
                        model.text = modelStrFenHao[1]
                        radio.text = modelStrFenHao[2]
                        androidClass.setText("22")
                        androidVersion.setText("5.1.1")
                        fingerprint.text = "${modelStrFenHao[0]}/${modelStrFenHao[1]}/${modelStrFenHao[2]}::5.1.1//XXX:/user/release-keys"
                        Board.text = "D310W"
                        Device.text = "D310W"
                        Product.text = "D310W"
                        host.text = "D310W-lz27x"
                        BuildI.text = "D310W_120712.08Z38"
                        var json = JSONObject()
                        json.put("imei           ".trim(), imei.text.toString())
                        json.put("androidID      ".trim(), androidID.text.toString())
                        json.put("wifiMac        ".trim(), wifiMac.text.toString())
                        json.put("wifiSSID       ".trim(), wifiSSID.text.toString())
                        json.put("phone          ".trim(), phone.text.toString())
                        json.put("sim            ".trim(), sim.text.toString())
                        json.put("imsi           ".trim(), imsi.text.toString())
                        json.put("simState       ".trim(), simState.text.toString())
                        json.put("firmID         ".trim(), firmID.text.toString())
                        json.put("frimName       ".trim(), frimName.text.toString())
                        json.put("cnCode         ".trim(), cnCode.text.toString())
                        json.put("model          ".trim(), model.text.toString())
                        json.put("firm           ".trim(), firm.text.toString())
                        json.put("radio          ".trim(), radio.text.toString())
                        json.put("androidClass   ".trim(), androidClass.text.toString())
                        json.put("androidVersion ".trim(), androidVersion.text.toString())
                        json.put("fingerprint    ".trim(), fingerprint.text.toString())
                        json.put("Board          ".trim(), Board.text.toString())
                        json.put("Device         ".trim(), Device.text.toString())
                        json.put("Product        ".trim(), Product.text.toString())
                        json.put("HOST           ".trim(), host.text.toString())
                        json.put("BuildID        ".trim(), BuildI.text.toString())
                        var paramsEntity = ParamsBean()
                        paramsEntity.paramsName = editStr
                        paramsEntity.paramsContent = json.toString()
                        paramsEntity.time = dateFormat.format(Date())
                        paramsDao.insert(paramsEntity)
                    } else {
                        Toast.makeText(this, "参数应该大于3位", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        //读取数据
            R.id.readData -> {
                var editStr = edit.text.toString()
                if (!TextUtils.isEmpty(editStr)) {
                    var parEntity = paramsDao.queryBuilder().where(ParamsBeanDao.Properties.ParamsName.eq(editStr)).build().unique()
                    setParams(parEntity.paramsContent)
                }
            }
        //随机生成
            R.id.randomGenerate -> {
                var params2 = parmas_2[random.nextInt(parmas_2.size)].split("|")
                phone.text = (getTel(params2[0]))
                imei.text = (getIMEI())
                imsi.text = (getImsi(params2[2]))
                sim.text = getICCID(params2[1])
                firmID.text = params2[1]
                wifiMac.text = (getMac())
                androidID.text = getStringIntRandom(15)
                wifiSSID.text = "TP-LINK_" + getIntRandom(4)
                simState.text = "5"
                var params1 = parmas_1[random.nextInt(parmas_1.size)].split("|")
                firm.text = params1[0]
                Board.text = params1[1]
                Device.text = params1[1]
                Product.text = params1[1]
                host.text = params1[1] + getStringIntRandom(5)
                model.text = params1[2]
                fingerprint.text = "${params1[0]}/${params1[1]}/${params1[2]}/user/release-keys"
            }
        //绑定参数
            R.id.bindParams -> {
            }
        //一键清理
            R.id.onekey -> {
                setPermission()
            }
        //清理设置
            R.id.clearSeting -> {
                intent = Intent(this, ClearSeting::class.java)
                startActivity(intent)
            }
        //历史记录
            R.id.hoisty -> {
                intent = Intent(this, History::class.java)
                startActivityForResult(intent, 101)
            }
        }
    }

    fun setParams(paramsContent: String) {
        var json = JSONObject(paramsContent)
        imei.text = json.getString("imei           ".trim())
        androidID.text = json.getString("androidID      ".trim())
        wifiMac.text = json.getString("wifiMac        ".trim())
        wifiSSID.text = json.getString("wifiSSID       ".trim())
        phone.text = json.getString("phone          ".trim())
        sim.text = json.getString("sim            ".trim())
        imsi.text = json.getString("imsi           ".trim())
        simState.text = json.getString("simState       ".trim())
        firmID.text = json.getString("firmID         ".trim())
        frimName.text = json.getString("frimName       ".trim())
        cnCode.text = json.getString("cnCode         ".trim())
        model.text = json.getString("model          ".trim())
        firm.text = json.getString("firm           ".trim())
        radio.text = json.getString("radio          ".trim())
        androidClass.setText(json.getString("androidClass   ".trim()))
        androidVersion.setText(json.getString("androidVersion ".trim()))
        fingerprint.text = json.getString("fingerprint    ".trim())
        Board.text = json.getString("Board          ".trim())
        Device.text = json.getString("Device         ".trim())
        Product.text = json.getString("Product        ".trim())
        host.text = json.getString("HOST           ".trim())
        BuildI.text = json.getString("BuildID        ".trim())
    }

    lateinit var paramsBeen: ParamsBean
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 101 && resultCode == 102) {
            paramsBeen = data.getParcelableExtra<ParamsBean>("params") as ParamsBean
            setParams(paramsBeen.paramsContent)
        }
    }

    fun setPermission() {
        //动态申请内存存储权限
        val rxPermissions = RxPermissions(this)
        rxPermissions.requestEach(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe { permission ->
                    if (permission.granted) {
                        // 用户已经同意该权限
                        //android.permission.RECORD_AUDIO
                        Log.d("yy", permission.name + " is granted.")
                        if (permission.name == "android.permission.WRITE_EXTERNAL_STORAGE") {
                            clearDir()
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        Log.d("yy", permission.name + " is denied. More info should be provided.")
                        Toast.makeText(this@MainActivity, "请允许" + permission.name, Toast.LENGTH_SHORT).show()
                        System.exit(0)
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        Log.d("yy", permission.name + " is denied.")
                        Toast.makeText(this@MainActivity, "请允许" + permission.name, Toast.LENGTH_SHORT).show()
                        System.exit(0)
                    }
                }
    }

    //清理目录下的文件
    private fun clearDir() {
        Toast.makeText(this, "正在清理", Toast.LENGTH_SHORT).show()
        var packNameStr = share.getstring(Constans.packName)
        var pathNameStr = share.getstring(Constans.pathName)
        var packName = packNameStr.split("\n")
        var pathName = pathNameStr.split("\n")
        for (p in pathName) {
            if (FileUtils.isDir(p)) {
                if (FileUtils.createOrExistsDir(p)) {
                    Log.w("yy", "正在删除目录>>$p")
                    FileUtils.deleteDir(p)
                }
            }
        }
        RootCmd.execRootCmd(packName)
        Toast.makeText(this, "清理完成！", Toast.LENGTH_SHORT).show()
    }

    @SuppressLint("MissingPermission")
    fun RunADB(adbContext: String): Boolean {
        var out: OutputStream? = null
        try {
            val process = Runtime.getRuntime()
            var proc = process.exec("su")
            var os = DataOutputStream(proc.outputStream)
            os.writeBytes("adb root\n")
            os.writeBytes("adb remount\n")
            os.writeBytes("$adbContext\n")
            os.flush()
            Log.w("yy", adbContext)
            var input = proc.inputStream
            var reader = InputStreamReader(proc.inputStream)
            var br = BufferedReader(reader)
            var str = ""
            var aa = true
            var sb = StringBuffer()
            while (aa) {
                str = br.readLine()
                if (str != null) {
                    sb.append(str)
                } else {
                    aa = false
                }
            }
            Log.w("yy", "<<<<${sb.toString()}")
            //adb shell am start -n com.pokercity.bydrqp.baidu/com.pokercity.bydrqp.lobby
            //out = process.outputStream
            //out!!.write(adbContext.toByteArray())
            //out.flush()
        } catch (e: IOException) {
            e.printStackTrace()
            Log.e("yy", " e: " + e.message)
            return false
        } finally {
            if (out != null) {
                try {
                    out.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
        return true

    }


    /**
     * 读TXT文件内容
     * @param filePath 文件路径(不要以 / 结尾)
     * @param fileName 文件名称（包含后缀,如：ReadMe.txt）
     * @return
     */
    private fun readTxtFile(inputstream: InputStream): String? {
        var result: String? = ""
        var bufferedReader: BufferedReader? = null
        val reader = InputStreamReader(inputstream)
        try {
            bufferedReader = BufferedReader(reader)
            try {
                var read: String? = null
                while ({ read = bufferedReader!!.readLine();read }() != null) {
                    result = result + read + "\r\n"
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close()
            }
        }
        println("读取出来的文件内容是：\r\n$result")
        return result
    }

    //生成ICCID
    fun getICCID(qz: String): String {
        return qz + getIntRandom(10)
    }

    var temp: Int = 0
    //生成随机数字和字母,
    private fun getStringIntRandom(length: Int): String {
        var str: StringBuffer = StringBuffer()
        //参数length，表示生成几位随机数
        for (i in 0 until length) {
            if (random.nextInt(2) % 2 == 0) {
                //输出是大写字母还是小写字母
                temp = if (random.nextInt(2) % 2 == 0) 65 else 97
                str.append((random.nextInt(26) + temp).toChar())
            } else {
                str.append(random.nextInt(10))
            }
        }
        return str.toString()
    }

    //生成随机数字
    private fun getIntRandom(length: Int): String {
        var str: StringBuffer = StringBuffer()
        val random = Random()
        //参数length，表示生成几位随机数
        for (i in 0 until length) {
            //输出数字
            str.append(random.nextInt(10).toString())
        }
        return str.toString()
    }

    /**
     * 返回手机号码
     */
    private fun getTel(qz: String): String {
        val second = (getNum(1, 888) + 10000).toString().substring(1)
        val third = (getNum(1, 9100) + 10000).toString().substring(1)
        return qz + second + third
    }

    private fun getNum(start: Int, end: Int): Int {
        return (Math.random() * (end - start + 1) + start).toInt()
    }

    //生成IMEI
    private fun getIMEI(): String {
        val r1 = 1000000 + java.util.Random().nextInt(9000000)
        val r2 = 1000000 + java.util.Random().nextInt(9000000)
        val input = r1.toString() + "" + r2
        val ch = input.toCharArray()
        var a = 0
        var b = 0
        for (i in ch.indices - 2) {
            val tt = Integer.parseInt(ch[i] + "")
            if (i % 2 == 0) {
                a += tt
            } else {
                val temp = tt * 2
                b += temp / 10 + temp % 10
            }
        }
        var last = (a + b) % 10
        if (last == 0) {
            last = 0
        } else {
            last = 10 - last
        }
        return "86$input$last"
    }

    //生成IMSI
    private fun getImsi(str: String): String {
        return str + getIntRandom(10)
    }

    //生成MAC
    private fun getMac(): String {
        val char1 = "abcdef".toCharArray()
        val char2 = "0123456789".toCharArray()
        val mBuffer = StringBuffer()
        for (i in 0..5) {
            val t = java.util.Random().nextInt(char1.size)
            val y = java.util.Random().nextInt(char2.size)
            val key = java.util.Random().nextInt(2)
            if (key == 0) {
                mBuffer.append(char2[y]).append(char1[t])
            } else {
                mBuffer.append(char1[t]).append(char2[y])
            }

            if (i != 5) {
                mBuffer.append(":")
            }
        }
        return mBuffer.toString()
    }
}
